package zuoye.Demo2.dao;
import Demo2.entity.Grade;
import Demo2.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class GradeDao implements Igrade {

    @Override
    public List<Grade> graAll() {
        List<Grade> list =new ArrayList<>();
        Connection conn =null;
        PreparedStatement ps =null;
        ResultSet rs =null;
        conn = DBUtil.getConnection();
        String sql ="select * from s_grade";
        try {
            ps =conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                Grade grade =new Grade();
                grade.setId(rs.getLong("id"));
                grade.setGname(rs.getString("gname"));
                list.add(grade);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(rs,ps,conn);
        }
        return list;
    }

    @Override
    public int graAdd(Grade g) {
        Connection conn =null;
        PreparedStatement ps =null;
        conn=DBUtil.getConnection();
        String sql ="INSERT INTO `s_grade` (`gname`) VALUES (?)";
        try {
            ps =conn.prepareStatement(sql);
            ps.setString(1,g.getGname());
            int num = ps.executeUpdate();
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(ps,conn);
        }
        return 0;
    }

    @Override
    public int graUpd(Grade g) {
        Connection conn =null;
        PreparedStatement ps =null;
        conn = DBUtil.getConnection();
        String sql ="UPDATE `s_grade` SET `gname` = ? WHERE `id` = ?";
        try {
            ps =conn.prepareStatement(sql);
            ps.setString(1,g.getGname());
            ps.setLong(2,g.getId());
            int num = ps.executeUpdate();
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(ps,conn);
        }
        return 0;
    }

    @Override
    public int graDel(long id) {
        Connection conn =null;
        PreparedStatement ps =null;
        conn = DBUtil.getConnection();
        String sql ="delete from s_grade where id=?";
        try {
            ps =conn.prepareStatement(sql);
            ps.setLong(1,id);
            int num = ps.executeUpdate();
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(ps,conn);
        }
        return 0;
    }
}
